import axios from "axios"

import { message } from "antd"

import { getToken, clearToken } from "@/utils/token"
import { history } from "@/utils/history"

const http = axios.create({
  baseURL: "http://localhost:8089",
  timeout: 5000
})

http.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const errData = error.response.data
    if (error.response.status === 401) {
      message.error("登陆已过期")
      clearToken()
      history.push("/")
    } else {
      errData?.message && message.error(errData?.message)
    }
    return Promise.reject(error)
  }
)

export default http
